<?php

namespace app\api\controller;

use app\common\controller\Api;
use think\Db;
use think\Exception;

/**
 * 首页接口
 */
class Index extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];

    /**
     * 首页
     *
     */
    public function index()
    {
        $sql=Db::name('push')->alias('p')
//            ->where('degree','>','over')
            ->field('*,degree-over as ti,id as t')
            ->buildSql();
//            ->where('degree-over','>','0')
//            ->select();

        echo '<pre>';
        var_dump($sql);
        var_dump(Db::name('push')->getLastSql());die;
        $this->success('请求成功');
    }

    public function sendTemplate($openid, $customer)
    {
//        Log::info('*************消息推送*******************');
        try {
            $res = self::initAccount()->template_message->send([
                'touser' => $openid,
                'template_id' => 'Xf9rCGiO4aYOp_qMYnof8dRYEVOgqtbHSFD5SEQzlOQ',
                'url' => 'http://crm.kuaijiangwangluo.com/mobile/#/pages/list/follow_customer_list',
                /* 'miniprogram' => [
                        'appid' => 'xxxxxxx',
                        'pagepath' => 'pages/xxx',
                ], */
                'data' => [
                    'keyword1' => $customer['customer_name'],
                    'keyword2' => $customer['phone'],
                    'keyword3' => '新客户',
                    'keyword4' => date('Y-m-d',time()),
                ],
            ]);
            Log::info('消息推送'.json_encode($res));
        } catch (Exception $e) {
            Log::error('消息推送：'.$e->getMessage());
            return false;
        }

    }

    public function getAccess()
    {


        $url='https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wxbb311d882903bb16&secret=e3f1414a1539cd75bed747ee667867f9';
        $params = array(
//            'param1' => 'value1',
//            'param2' => 'value2'
        );
//        try {
            $response = $this->sendHttpRequest($url, 'GET', $params);
            $res=json_decode($response,true);
            return $res['access_token'];
//            var_dump($res);
//            echo "Response: " . $response;
//        } catch (Exception $e) {
//            echo "Error: " . $e->getMessage();
//        }
    }


    /**
     * @param $openid
     * @param $board
     * @param $push
     * @param $time   //当前是第几次
     * @return bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException\
     *
     */
    public function send($openid,$board,$push,$time)
    {
        $access=$this->getAccess();

        $url='https://api.weixin.qq.com/cgi-bin/message/template/send?access_token='.$access;
        $data=explode(',',$board['content']);
        $cate=Db::name('cate')->where('id',$board['cate_id'])->find();
        if($push['type']=='1'){
            $st=bcmul($time,$push['number']).'周';
        }else{
            $st=bcmul($time,$push['number']).'月';
        }
        $params = [
            'touser' => $openid,
            'template_id' => $board['wx_id'],
            'data' => [
                $data['0']=>[
                    'value'=>$cate['name'].$board['name'],
                ],
                $data['1']=>[
                    'value'=>'首次治疗后'.$st,
                ],
                $data['2']=>[
                    'value'=>'请与近日来医院复查',
//                    'value'=>'一级告警',
                ],
            ]
        ];
//        var_dump($params);
        $params=json_encode($params);
//        try {
            $response = $this->sendJsonPostRequest($url,  $params);
            echo "Response: " . $response;
            return true;

//        } catch (Exception $e) {
//            return false;
//            echo "Error: " . $e->getMessage();
        }







    public function sendJsonPostRequest($url, $jsonData) {
        $ch = curl_init();

        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonData);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
            'Content-Type: application/json',
            'Content-Length: ' . strlen($jsonData)
        ));
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

        $response = curl_exec($ch);

        if ($response === false) {
            $error = curl_error($ch);
            curl_close($ch);
            throw new Exception("cURL Error: " . $error);
        }

        curl_close($ch);

        return $response;
    }


    function sendHttpRequest($url, $method = 'GET', $params = []) {
        $ch = curl_init();

        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

        if ($method === 'POST') {
            curl_setopt($ch, CURLOPT_POST, true);
            curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($params));
        } elseif ($method === 'GET' && !empty($params)) {
            $url .= (strpos($url, '?') === false ? '?' : '&') . http_build_query($params);
        }

        $response = curl_exec($ch);

        if ($response === false) {
            $error = curl_error($ch);
            curl_close($ch);
            throw new Exception("cURL Error: " . $error);
        }

        curl_close($ch);

        return $response;
    }

}
